'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username&&password){  //非空  容错处理
            //1.排重
            let selectUser = await service.user.selectUser(username);
            if(selectUser.length){
                ctx.body = {
                    code:3,
                    msg:'此用户名已存在'
                }
            }else{
                //密码暗文
                let hmcPwd = ctx.helper.hmc(password);
                try{
                    await service.user.registry(username,hmcPwd);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }   
    }
    //登录
    async login(){
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;
        if(username&&password){  //非空  容错处理
            let hmcPwd = ctx.helper.hmc(password);
            let user = await service.user.login(username,hmcPwd);
            if(user.length){
                let {id,username} = user[0];
                let token = jwt.sign({uid:id},'yuque',{expiresIn:60*60*4})
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    uid:id,
                    username:username
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //编辑个人信息
    async editPerson(){
        let {ctx,service} = this;
        let {username,password,id,intro} = ctx.request.body;
        if(username&&password&&id){  //非空  容错处理
            try{
                let hmcPwd = ctx.helper.hmc(password);
                await service.user.editPerson(username,hmcPwd,intro,id);
                ctx.body = {
                    code:1,
                    msg:'修改成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }   
    }
}

module.exports = UserController;
